package com.jk.log.controller;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.jk.log.pojo.LogPojo;

public class AopDemo implements AfterReturningAdvice {

	/*@Resource（name=“AomRapsService”）*/
//	@Autowired
//	private MongoTemplate mongoTemplate;
	
	
	//returnVals:返回值      method :方法的对象        params: 方法的参数    url：实现类的类路径

	@Before("execution(* com.jk.**.service.impl.*.*(..))")
	public void afterReturning(Object returnVals, Method method, Object[] params, Object url) throws Throwable {
		
		System.out.println("前置通知");
	
		LogPojo logPojo = new LogPojo();
		/*logPojo.setReturnvals(returnVals);*/
		logPojo.setMethodname(method.getName());
		/*String param = "";
	    if (params != null && params.length > 0){
	    	for (int i = 0; i < params.length; i++) {
		     	param += "参数[" + i + "]:" + params[i].toString();
		    }
	    }else{
	    	param = "NoParam";
	    }
		logPojo.setParams(param);*/
		logPojo.setUrlstr(url.toString());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		logPojo.setActtime(sdf.format(new Date()));
		logPojo.setState(1);
		logPojo.setExceptionInfo("NoException");
		System.err.println(method.getName());
		System.out.println("---------------------------------------");
//		mongoTemplate.insert(logPojo);
		
	}
	
	
	  /**
     * 在目标方法出现异常时会执行的代码
     * 可以访问出现的异常信息，可以指定出现指定异常时执行
     * 方法参数Exception改为其它异常可以指定出现指定异常时执行
     * @param joinPoint
     * @param
     */
    @AfterThrowing(value="execution(* com.jk.**.service.impl.*.*(..))",
            throwing="error")
    public  void afterThrowing(JoinPoint joinPoint,Throwable error,Object url){
    	
        System.err.println("异常通知");
        
        try {
			
		
		LogPojo logPojo = new LogPojo();
		String methodName=joinPoint.getSignature().getName();
		logPojo.setMethodname(methodName);
		logPojo.setUrlstr(url.toString());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		logPojo.setActtime(sdf.format(new Date()));
		//异常详细信息
		String message = error.getMessage();
		logPojo.setExceptionInfo(message);
		logPojo.setState(2);
//		mongoTemplate.insert(logPojo);
		System.err.println("The method "+methodName+" occurs exection: "+ error);
		
        } catch (Exception ex) {
			// TODO: handle exception
		}
    }

}